using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using System.Transactions;
using HengTong.Model;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using TiaoTaoHelper.Wtm.Workflow;
using Microsoft.Extensions.DependencyInjection;
using HengTong.Model.Db;
using HengTong.Model.Db.Hr.Attendance;
using HengTong.Model.Services;
using TiaoTaoHelper.Models;
using UUIDNext;
using HengTong.Model.Db.Hr.Attendance.Rule;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Extension.String;


namespace HengTong.ViewModel.Hr.SysAttendanceShiftVms
{
    public partial class SysAttendanceShiftVm : CrudVm<SysAttendanceShift>
    {

        [Display(Name = "工作日")] public List<string> WorkDays { get; set; } = [];
        
        public SysAttendanceShiftVm()
        {
            SetInclude(x => x.SubsidyRules);
        }

        protected override void InitVM()
        {
            if (Entity != null && !string.IsNullOrWhiteSpace(Entity.WorkDays) && Entity.WorkDays.TryJsonParse(out List<string> days))
            {
                WorkDays = days;
            }
        }

        public override async Task DoAddAsync()
        {
            if (Entity.IsDefault)
            {
                await DC.Set<SysAttendanceShift>()
                    .Where(e => e.IsDefault == true)
                    .ExecuteUpdateAsync(e => e.SetProperty(p => p.IsDefault, p => false));
            }
            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            Entity.WorkDays = JsonSerializer.Serialize(WorkDays);
            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            if (Entity.IsDefault)
            {
                await DC.Set<SysAttendanceShift>()
                    .Where(e => e.IsDefault == true)
                    .ExecuteUpdateAsync(e => e.SetProperty(p => p.IsDefault, p => false));
            }
            Entity.WorkDays = JsonSerializer.Serialize(WorkDays);
            await base.DoEditAsync(updateAllFields);
        }

    }
}
